<template>
    <div class="add" id="add">
        <van-cell-group>
            <van-field
                :value="form.receiver"
                label="收货人"
                placeholder="请输入用户名"
                :border="false"
                @change="(e) => headleChange(e, { receiver: '' })"
            />
            <van-field
                :value="form.mobile"
                label="手机号码"
                placeholder="11位手机号码"
                :border="false"
                @change="(e) => headleChange(e, { mobile: '' })"
            />
            <picker
                mode="multiSelector"
                @columnchange="headlePicker"
                range-key="areaName"
                :value="val"
                :range="[provinceList, cityList, areaList]"
            >
                <van-field
                    :value="alladdress"
                    label="所在地区"
                    placeholder="地址"
                    :border="false"
                />
            </picker>
            <van-field
                :value="form.addr"
                label="详细地址"
                placeholder="如楼号/单元/门牌号"
                :border="false"
                @change="(e) => headleChange(e, { addr: '' })"
            />
        </van-cell-group>
        <button class="success" @click="onClickButton">保存收货地址</button>
        <template v-if="!!form.addrId">
            <button class="lose" @click="onClickDelete">删除收货地址</button>
        </template>
        <van-loading v-if="loading" size="24px" vertical />
        <van-dialog id="van-dialog" />
        <template v-if="toastShow">
            <Toast :toastText="toastText" />
        </template>
    </div>
</template>

<script>
import { mapActions } from 'vuex';
import { getEdit, deleteEdit, updateEdit, getAreaByPid } from '@/services';
import Dialog from '@/static/dist/dialog/dialog';
import Toast from '@/components/Toast';
export default {
    async mounted() {
        if (this.$mp.query.addrId) {
            this.form.addrId = this.$mp.query.addrId;
            const result = await getEdit(this.form.addrId);
            this.form = result;
            this.headleIndex();
        }
    },
    created() {
        const arealist = setTimeout(async () => {
            if (wx.getStorageSync('access_token')) {
                const result = await getAreaByPid(0);
                this.provinceList = result;
                this.form.provinceId = result[0].areaId;
                this.curProvinceId = result[0].areaId;
                this.form.province = result[0].areaName;
                clearTimeout(arealist);
            }
        }, 400);
    },
    components: {
        Toast,
    },
    data() {
        return {
            loading: false, //
            provinceList: [],
            areaList: [],
            cityList: [],
            jsq: 0,
            curProvinceId: 0,
            curCityId: 0,
            curAreaId: 0,
            val: [0, 0, 0],
            toastShow: false, //弹框状态
            toastText: '', //提示内容
            form: {
                receiver: '', //名字
                mobile: '', //手机号
                city: '', //区
                area: '', //市
                province: '', //省
                addr: '', //详细地址
                addrId: 0,
                areaId: 0,
                cityId: 0,
                provinceId: 0,
                userType: 0,
            },
        };
    },
    watch: {
        async curProvinceId(value) {
            if (this.$mp.query.addrId && this.jsq < 3) {
                const res = await getAreaByPid(this.form.provinceId);
                this.cityList = res;
                this.curCityId = this.form.cityId;
                this.jsq++;
                this.headleIndex();
                return;
            }
            const result = await getAreaByPid(value);
            this.cityList = result;
            this.form.cityId = result[0].areaId;
            this.curCityId = result[0].areaId;
            this.form.city = result[0].areaName;
        },
        async curCityId(value) {
            if (this.$mp.query.addrId && this.jsq < 5) {
                const res = await getAreaByPid(this.form.cityId);
                this.areaList = res;
                this.jsq++;
                this.headleIndex();
                return;
            }
            console.log(value);
            const result = await getAreaByPid(value);
            this.areaList = result;
            this.form.areaId = result[0].areaId;
            this.curAreaId = result[0].areaId;
            this.form.area = result[0].areaName;
        },
    },
    computed: {
        alladdress() {
            return (
                `${this.form.province} ${this.form.city} ${this.form.area}` ||
                '请选择地址'
            );
        },
    },
    methods: {
        ...mapActions({
            getList: 'address/getList',
            postAdd: 'address/postAdd',
        }),
        // 添加或保存
        async onClickButton() {
            if (this.form.receiver === '') {
                this.headleToast('请输入收货人姓名');
                return;
            }
            if (this.form.mobile === '') {
                this.headleToast('请输入手机号码');
                return;
            }
            if (!/^1[3-9]\d{9}$/.test(this.form.mobile)) {
                this.headleToast('请正确输入手机号码');
                return;
            }
            if (this.form.addr === '') {
                this.headleToast('请输入详细地址');
                return;
            }
            if (this.$mp.query.addrId) {
                const result = await updateEdit(this.form);
                if (result === '修改地址成功') {
                    this.getList();
                }
            } else {
                this.postAdd(this.form);
            }
            wx.navigateBack();
        },
        // 删除
        onClickDelete() {
            Dialog.confirm({
                message: '确定要删除此收货地址吗？',
            })
                .then(async () => {
                    const result = await deleteEdit(this.form.addrId);
                    if (result.status === 400) {
                        this.headleToast('默认地址无法删除');
                        return;
                    }
                    this.loading = true;
                    setTimeout(() => {
                        this.loading = false;
                        wx.navigateBack();
                    }, 1000);
                    this.getList();
                })
                .catch(() => {
                    // on cancel
                });
        },
        // 输入框事件
        headleChange(e, obj) {
            const { detail } = e;
            for (let key in obj) {
                this.form[key] = detail;
            }
        },
        // 提示弹框
        headleToast(info) {
            this.toastShow = true;
            this.toastText = info;
            setTimeout(() => {
                this.toastShow = false;
            }, 1000);
        },
        headlePicker({ detail: { column, value } }) {
            this.val[column] = value;
            switch (column) {
                case 0:
                    this.form.provinceId = this.provinceList[value].areaId;
                    this.curProvinceId = this.provinceList[value].areaId;
                    this.form.province = this.provinceList[value].areaName;
                    break;
                case 1:
                    this.form.cityId = this.cityList[value].areaId;
                    this.curCityId = this.cityList[value].areaId;
                    this.form.city = this.cityList[value].areaName;
                    break;
                case 2:
                    this.form.areaId = this.areaList[value].areaId;
                    this.curAreaId = this.areaList[value].areaId;
                    this.form.area = this.areaList[value].areaName;
                    break;
                default:
                    break;
            }
            if (column < 2) {
                for (let i = column; i < 2; i++) {
                    this.val[i + 1] = 0;
                }
                console.log(this.val);
            }
        },
        headleIndex() {
            const info = JSON.parse(wx.getStorageSync('city'));
            this.form = info;
            setTimeout(() => {
                const provinceIndex = this.provinceList.findIndex(
                    (item) => item.areaName == info.province
                );
                const cityIndex = this.cityList.findIndex(
                    (item) => item.areaName == info.city
                );
                const areaIndex = this.areaList.findIndex(
                    (item) => item.areaName == info.area
                );
                this.val = [provinceIndex, cityIndex, areaIndex];
                this.curProvinceId = info.provinceId;
            }, 1000);
        },
    },
};
</script>

<style lang="scss" scoped>
#add button {
    display: flex;
    align-items: center;
}
#add .success{
    background: red;
    color:#fff
}
#add .lose{
    border:1px solid red;
    color:red;
}
#add button {
    margin-top: 10px;
    border-radius: 100px;
    text-align: center;
    display: flex;
    justify-content: center;
    font-size: 26px;
    width: 80%;
}
</style>
